package com.dean.service;

import cn.hutool.core.util.StrUtil;
import com.dean.exception.DeanRuntimeException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;

/**
 * Pdf 代码合并
 */
public class PdfMergeService {
    private final static Logger logger = LoggerFactory.getLogger(PdfMergeService.class);

    private PdfMergeService(){
    }
    private static volatile PdfMergeService INSTANCE;
    public static PdfMergeService getInstance(){
        if(INSTANCE == null){
            synchronized (PdfMergeService.class){
                if(INSTANCE == null){
                    INSTANCE = new PdfMergeService();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 合并pdf
     * @param files  需要合并的文件
     * @param targetPath 目标文件名
     */
    public void pdfMerge(File [] files,String targetPath){
        Document document = null;
        PdfCopy copy = null;
        PdfReader reader = null;
        try{
            document = new Document(new PdfReader(files[0].getPath()).getPageSize(1));
            copy = new PdfCopy(document,new FileOutputStream(targetPath));
            document.open();
            for (int i = 0; i < files.length; i++) {
                reader = new PdfReader(files[i].getPath());
                int pages = reader.getNumberOfPages();
                for (int j = 1; j <= pages; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader,j);
                    copy.addPage(page);
                }
            }
        }catch (IOException ioException){
            logger.error(ioException.getMessage(),ioException);
            throw DeanRuntimeException.throwException(9999,"系统错误:"+ioException.getMessage());
        }catch (DocumentException documentException){
            logger.error(documentException.getMessage(),documentException);
            throw DeanRuntimeException.throwException(9999,"系统错误:"+documentException.getMessage());
        }finally {
            if(reader != null){
                reader.close();
            }
            if(copy != null){
                copy.close();
            }
        }

    }


    public void pdfMerge(String sourcePath,String targetPath){
        // 参数校验
        if(StrUtil.isBlank(sourcePath)){
            throw DeanRuntimeException.throwException(2001,"校验错误,参数[sourcePath]不能为空");
        }
        if(StrUtil.isBlank(targetPath)){
            throw DeanRuntimeException.throwException(2001,"校验错误,参数[targetPath]不能为空");
        }
        File file = new File(sourcePath);
        File [] files = file.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if(name.endsWith(".pdf")){
                    return true;
                }
                return false;
            }
        });
        if(files!=null && files.length > 0 ){
           pdfMerge(files,targetPath);
        }
    }

    private void close(Document document,PdfReader reader,PdfCopy copy){
        close(document);
        close(reader);
        close(copy);
    }

    private void close(Document document){
        if(document != null){
            document.close();
        }
    }
    private void close(PdfReader reader){
        if(reader != null){
            reader.close();
        }
    }
    private void close(PdfCopy copy){
        if(copy != null){
            copy.close();
        }
    }
}
